package UsersPackage;

import Util.DBUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/login.do")
public class LoginCheckServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (username != null && !username.isEmpty() && password != null && !password.isEmpty()) {
            Connection conn;
            PreparedStatement stmt;
            ResultSet rs;

            try {
                conn = DBUtil.getConnection();
                String sql = "SELECT user_id, username, password ,power FROM user WHERE username = ? AND password = ?";
                stmt = conn.prepareStatement(sql);
                stmt.setString(1, username);
                stmt.setString(2, password);
                rs = stmt.executeQuery();

                if (rs.next()) {
                    // 合法用户，重定向到欢迎页面
                    String user_id = rs.getString("user_id");
                    boolean power = rs.getBoolean("power");
                    HttpSession session = request.getSession();
                    session.setAttribute("user_id", user_id);
                    session.setAttribute("username", username);
                    session.setAttribute("power", power);
                    response.sendRedirect("first.jsp");
                } else {
                    // 非法用户，显示错误消息并退回登录页面
                    response.getWriter().println("<p>错误的账号或者密码，请重新输入(将等待3秒后跳转)</p>");
                    // 添加以下代码来进行页面重定向
                    response.setHeader("Refresh", "3;url=Register.jsp"); // 在3秒后跳转回登录页面
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // 用户名或密码为空，显示错误消息并退回登录页面
            response.getWriter().println("<p>账号密码不能为空.</p>");
            // 添加以下代码来进行页面重定向
            response.setHeader("Refresh", "3;url=Register.jsp"); // 在3秒后跳转回登录页面
        }
    }
}